package com.pig.graduate.common.timing;


import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig.graduate.domain.material.MaterialInventory;
import com.pig.graduate.domain.material.MaterialStorage;
import com.pig.graduate.mapper.material.MaterialInventoryMapper;
import com.pig.graduate.mapper.material.MaterialStorageMapper;
import com.pig.graduate.service.material.MaterialInventoryService;
import com.pig.graduate.service.material.MaterialStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class MyTiming {

    @Autowired
    private MaterialStorageService materialStorageService;

    @Scheduled(cron="0 0 12 * * ?")   //每晚12点执行一次
    public void execute(){
        List<MaterialStorage> list = materialStorageService.getMaterialsNoOverdue();
        List<MaterialStorage> reList = new ArrayList<>();
        for (MaterialStorage materialStorage : list) {
            Long betweenDay = DateUtil.between(materialStorage.getDateOfManufacture(), new Date(), DateUnit.DAY);
            Long difference = betweenDay - Long.parseLong(materialStorage.getShelfLife());
            if(difference < 0){
                materialStorage.setState(2);
                reList.add(materialStorage);
            }else if(difference < Integer.parseInt(materialStorage.getExpiryReminders())){
                materialStorage.setState(1);
                reList.add(materialStorage);
            }
        }
        materialStorageService.updateBatchById(reList);
    }
}
